package org.duiduo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.duiduo.common.bean.BookVO;
import org.duiduo.common.request.BookDeleteBatchRequest;
import org.duiduo.common.request.BookFindPageRequest;
import org.duiduo.entity.Book;
import org.duiduo.mapper.BookMapper;
import org.duiduo.service.BookService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Override
    public Page<Book> findPage(BookFindPageRequest request) {
        Page<Book> page = new Page<>(request.getPageNum(), request.getPageSize());
        LambdaQueryWrapper<Book> wrapper = Wrappers.<Book>lambdaQuery();
        if (StrUtil.isNotBlank(request.getSearch())) {
            wrapper.like(Book::getName, request.getSearch());
        }
        return bookMapper.selectPage(page, wrapper);
    }

    @Override
    public int deleteById(Integer id) {
        return bookMapper.deleteById(id);
    }

    @Override
    public int save(BookVO bookVO) {
        Book book = new Book();
        BeanUtil.copyProperties(bookVO, book, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        return bookMapper.insert(book);
    }

    @Override
    public int update(BookVO bookVO) {
        Book book = new Book();
        BeanUtil.copyProperties(bookVO, book, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        return bookMapper.updateById(book);
    }

    @Override
    public int deleteBatch(BookDeleteBatchRequest request) {
        return bookMapper.deleteBatchIds(request.getIds());
    }
}
